package com.jic.product.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.product.entity.ProductParameter;
import com.jic.product.mapper.ProductParameterMapper;
import com.jic.product.model.vo.request.ParameterJsonRequest;
import com.jic.product.model.vo.request.ParameterJsonUpdateRequest;
import com.jic.product.model.vo.request.ProductParameterAddRequest;
import com.jic.product.model.vo.response.ParameterJsonResponse;
import com.jic.product.model.vo.response.ProductParameterListResponse;
import com.jic.product.service.ProductParameterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-10-04 19:03:20
 */
@Service
@Slf4j
public class ProductParameterServiceImpl implements ProductParameterService {

	@Resource
	private ProductParameterMapper productParameterMapper;
	@Autowired
	private RedisClientTemplate redisClientTemplate;

	@Override
	public Long add(ProductParameterAddRequest addRequest) {
		ProductParameter productParameter = new ProductParameter();
		BeanUtils.copyProperties(addRequest,productParameter);
		String token = addRequest.getToken();
		String userStr = redisClientTemplate.get(token);
		Map<String,Object> user = JSONArray.parseObject(userStr, Map.class);
		productParameter.setCreator(Long.valueOf(user.get("id").toString()));
		productParameter.setCreatorName(user.get("username").toString());
		productParameterMapper.insert(productParameter);
		return productParameter.getId();
	}

	@Override
	public List<ProductParameterListResponse> listAll(Long categoryId) {
		return productParameterMapper.listAll(categoryId);
	}

	@Override
	public int delete(Long id) {
		return productParameterMapper.delete(id);
	}

	@Override
	public ParameterJsonResponse getParameterJson(ParameterJsonRequest request) {
		ParameterJsonResponse response = new ParameterJsonResponse();
		// 查询参数json字段
		String parameterJson = productParameterMapper.findParameterJsonById(request.getProductId());
		response.setParameterJson(parameterJson);
		// 查询分类参数
		List<ProductParameterListResponse> templateList = productParameterMapper.listAll(request.getCategoryId());
		response.setTemplateList(templateList);
		return response;
	}

	@Override
	public int updateParameterJson(ParameterJsonUpdateRequest updateRequest) {
		return productParameterMapper.updateParameterJson(updateRequest);
	}

}
